directives.directive('chartDashPie', ['$rootScope','sonCatSalesPieServ','Session','tools','sonCatSalesServ','$timeout',function ($rootScope,sonCatSalesPieServ,Session,tools,sonCatSalesServ,$timeout) {
	return {
		restrict: 'E',
		scope:{},
		repalce:true,
		templateUrl:'app/pages/dashBroad/chart-dash-pie/chartDashPieView.html',
		link: function (scope, element, attrs) {
			console.log('chart-dash-pie.js');
			var evs = {};
            var cats = [];
            var dim = "sellMoney";
            var catName, category;
            var $backTop = $(element).find('.backTop');
            var $backLast = $(element).find('.backLast');
            var myChart = myChart = echarts.init($(element).find('.chart-container')[0], 'westeros');

            scope.userInfo = Session.UserInfo ||{};

            // console.log(scope.userInfo);


            //my-full-func
            scope.screenResize = function(){
                myChart.resize();
            }

            scope.chartType = 'pie';
            scope.switchChartType = function (nt) {
                myChart.clear();
                scope.chartType = nt;
                drawChart(catName, category);
            }

            // 类目占比饼图
            var option_for_pie = {
                tooltip: {
                    trigger: 'item',
                    formatter: function (params) {
                        // console.log(params);
                        var str = '<div style = "text-align: center;">' + params.name + '</div>';

                        str += '<div style = "text-align: left;padding-left:10px;">' + params.seriesName + ' : ' + tools.bigNumFormat(params.value) + '('+params.percent+'%)</div>';

                        return str;
                    }
                },
                legend: {
                    orient: 'vertical',
                    left: 'left'
                },
                series: [
                {
                    name: '销售额',
                    type: 'pie',
                    radius: '60%',
                    center: ['50%', '55%'],                  
                    data: [],
                    itemStyle: {
                        emphasis: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
                ]
            };

            var option_for_bar = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                    },
                    formatter: function (params) {
                        var str = '<div style = "width:120px;text-align: left;">' + params[0].name + '</div>';

                        for (var i = 0; i < params.length; i++) {
                            str += '<div style = "width:120px;text-align: left;padding-left:10px;">' + params[i].seriesName + ' : ' + tools.bigNumFormat(params[i].value) + '</div>';
                        }

                        return str;
                    }
                },
                legend: {
                    data: []
                },
                grid: {
                    left: 40,
                    bottom: 70,
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: cats,
                    axisLabel: {
                        rotate: 37,
                        interval: 0
                    }
                },
                yAxis: {
                    type: 'value',
                    axisLabel: {
                        formatter: function (value, index) {
                            var len = String(value).length;

                            if (value < 10000) {
                                return value;
                            }

                            switch (len) {
                                case 5:
                                return (value / 10000)+ '万';
                                case 6:
                                return (value / 10000) + '万';
                                case 7:
                                return (value / 10000) + '万';
                                case 8:
                                return (value / 10000) + '万';
                                case 9:
                                return (value / 100000000) + '亿';
                                case 10:
                                return (value / 100000000) + '亿';
                                case 11:
                                return (value / 100000000) + '亿';
                                case 12:
                                return (value / 100000000) + '亿';
                            }

                            return value;
                        }
                    }
                },
                series: [
                {
                    name: '销售额',
                    type: 'bar',
                    data: []
                }
                ]
            };

            var drawChart = function (catName_, category_) {
                var option = scope.chartType == 'pie' ? option_for_pie : option_for_bar;

                cats.length = 0;
                scope.isLastCategory = false; //是否展示词云html
                // 如果不能再继续下钻则直接返回
                if (category_) {
                    // console.log('不能再继续下钻')
                    $timeout(function(){
                        // console.log('scope.isLastCategory:'+scope.isLastCategory);
                        scope.isLastCategory = true; //是否展示词云html
                    },10);
                    myChart.showLoading();
                    sonCatSalesPieServ.getData(catName_, category_, function (resp) {
                        if (resp.success) {

                            scope.yuetitle = catName_.split('--')[catName_.split('--').length - 1] + '下不同平台销售额对比';
                   
                            option.series[0].data.length = 0;

                            option.series[0].data.push({
                                name: '天猫',
                                value: resp.value[0].tSellMoney
                            });
                            cats.push('天猫');

                            option.series[0].data.push({
                                name: '淘宝',
                                value: resp.value[0].cSellMoney
                            });
                            cats.push('淘宝');

                            myChart.setOption(option);
                            myChart.hideLoading();
                            myChart.off('click');
                        }
                    });
                    return;
                }

                myChart.off('click');
                myChart.showLoading();

                sonCatSalesPieServ.getData(catName_, category_, function (resp) {
                    if (resp.success) {
                        scope.yuetitle= (catName_ != '/' ? catName_.split('--')[catName_.split('--').length - 1] : '全网') + '各子类目销售额对比';
        
                        option.series[0].data.length = 0;

                        resp.value.sort(function (n, m) {
                            return m[dim] - n[dim];
                        });
                        // console.log(resp.value);
                        for (var i = 0; i < resp.value.length; i++) { 
                            if(i>24 && scope.chartType == 'pie'){
                                option.series[0].data.push({
                                    name: resp.value[i].categoryName.split('--')[resp.value[i].categoryName.split('--').length - 1],
                                    value: resp.value[i].sellMoney,
                                    label:{
                                        normal:{
                                            show:false,
                                            textStyle:{
                                                fontSize:12
                                            }
                                        },
                                        emphasis:{
                                            show: true,
                                            textStyle:{
                                                fontSize:18,
                                                fontWeight:800
                                            }
                                        }
                                    },
                                    labelLine:{
                                        normal:{
                                            show:false,
                                            smooth:true,
                                            lineStyle: {
                                                opacity:0.7
                                            }, 
                                        },
                                        emphasis:{
                                            show: true,
                                            lineStyle: {
                                                width: 3,
                                                opacity:1
                                            },
                                        }
                                    }
                                });
                                
                            }else{
                                if(scope.chartType == 'pie'){
                                    option.series[0].data.push({
                                        name: resp.value[i].categoryName.split('--')[resp.value[i].categoryName.split('--').length - 1],
                                        value: resp.value[i].sellMoney,
                                        label:{
                                            normal:{
                                                show:true,
                                                textStyle:{
                                                    fontSize:12
                                                }
                                            },
                                            emphasis:{
                                                show: true,
                                                textStyle:{
                                                    fontSize:18,
                                                    fontWeight:800
                                                }
                                            }
                                        },
                                        labelLine:{
                                            normal:{
                                                show:true,
                                                lineStyle: {
                                                    opacity:0.7
                                                },                                            
                                            },
                                            emphasis:{
                                                show: true,
                                                lineStyle: {
                                                    width: 3,
                                                    opacity:1
                                                },
                                            }
                                        }
                                    });
                                }else{
                                    option.series[0].data.push({
                                        name: resp.value[i].categoryName.split('--')[resp.value[i].categoryName.split('--').length - 1],
                                        value: resp.value[i].sellMoney
                                    });
                                }
                            }
                            

                            cats.push(resp.value[i].categoryName.split('--')[resp.value[i].categoryName.split('--').length - 1]);
                        }
                        // console.log(option.series[0].data);
                        myChart.setOption(option);
                        myChart.resize();
                        myChart.hideLoading();

                        // 如果下面还有叶子类目则
                        if (!category_) {
                            // 获取类目数据
                            sonCatSalesServ.getItemCategory(catName_, function (resp) {
                                if (resp.success) {
                                    var sonCats = resp.value;

                                    myChart.on('click', function (param) {
                                        // 广播被选中的类目信息
                                        if (sonCatSalesServ.getCategoryByName(param.name, sonCats)) {
                                            $rootScope.$broadcast('GLOBAL_CATEGORY_CHANGE_EV', catName_ != '/' ? catName_ + '--' + param.name : param.name, sonCatSalesServ.getCategoryByName(param.name, sonCats));
                                        } else {
                                            $rootScope.$broadcast('GLOBAL_CATEGORY_CHANGE_EV', catName_ != '/' ? catName_ + '--' + param.name : param.name, null);
                                        }
                                    });
                                }
                            });
                        }
                    }
                });
            }

            
            
            evs.GLOBAL_CATEGORY_CHANGE_EV_OFF = $rootScope.$on('GLOBAL_CATEGORY_CHANGE_EV', function (e, catName_, category_) {
                // console.log('catName_:'+catName_)
                // console.log('category_:'+category_)            
                if(!scope.userInfo){
                    scope.userInfo = Session.UserInfo;
                }
                // console.log(tp)
                drawChart(catName = catName_, category = category_);
                
                if (catName == '/') {
                    $backLast.hide();
                    $backTop.hide();
                } else {
                    var tp = scope.userInfo.itemLevel1Category;
                    if(tp){
                        if(catName_ == tp){
                            $backLast.hide();
                            $backTop.hide();
                        }else{
                            $backLast.show();
                            $backTop.show();
                        }
                    }else{
                        $backLast.show();
                        $backTop.show();
                    }

                }
            });


            
            evs.DIMENSION_CHANGE_EV_OFF = $rootScope.$on('DIMENSION_CHANGE_EV', function (e, dim_) {

            });

            $backLast.click(function () {
                category = null;
                if (catName.indexOf('--') != -1) {
                    catName = catName.split('--').slice(0, catName.split('--').length - 1).join('--');
                } else {
                    catName = '/';
                }

                $rootScope.$broadcast('GLOBAL_CATEGORY_CHANGE_EV', catName, category);
            });

            $backTop.click(function () {
                category = null;
                // catName = '/';
                var tp
                if(scope.userInfo.channel == '0'){
                    tp = scope.userInfo.itemLevel1Category;
                }

                catName = tp?tp:'/';
                if(tp.indexOf('?')!==-1){
                    catName = '/';
                }
                $rootScope.$broadcast('GLOBAL_CATEGORY_CHANGE_EV', catName, category);
            });

            //跳转到词云
            scope.toWordCloud = function(){
                var ss = JSON.stringify({category:category,catName:catName});
                tools.data.setItem('word',ss);
                $rootScope.$broadcast('toWordCloud_EV',category,catName);                
                $location.path('/industryWord');
            }
            scope.$on('$destroy', function () {
                for (var i in evs) {
                    if (i.indexOf('_OFF') != -1) {
                        evs[i]();
                    }
                }
            });
		}
	};
}]);
services.factory('sonCatSalesPieServ', ["$http", "$rootScope", "$timeout", "tools", function ($http, $rootScope, $timeout, tools) {
    return {
        getData: function (catName, category, cb) {
            var self = this;

            if (self.cache && self.cache[catName]) {
                cb && cb(self.cache[catName]);
                return;
            }

            tools.get({
                url: '/marketconditions/statistic/' + (category ? 'getCategoryStatistic' : 'getCategoryStatistics') + '.htm',
                data: {
                    catName: catName
                },
                succ: function (resp) {
                    $rootScope.$broadcast('CATEGORY_DATA_EV', resp.value);

                    angular.forEach(resp.value, function (item) {
                        item.avgPrice = item.sellMoney / item.sellAmount;
                        item.tAvgPrice = item.tSellMoney / item.tSellAmount;
                        item.cAvgPrice = item.cSellMoney / item.cSellAmount;
                    });

                    cb && cb(resp);

                    if (!self.cache) {
                        self.cache = {};
                    }
                    self.cache[catName] = resp;
                }
            });
        }
    }
}]);
services.factory('sonCatSalesServ', ["$http", "$rootScope", "$timeout", "tools", function ($http, $rootScope, $timeout, tools) {
    return {
        getData: function (catName, category, cb) {
            var self = this;

            if (self.cache && self.cache[catName]) {
                cb && cb(self.cache[catName]);
                return;
            }

            tools.get({
                url: '/marketconditions/statistic/' + (category ? 'getCategoryStatistic' : 'getCategoryStatistics') + '.htm',
                data: {
                    catName: catName
                },
                succ: function (resp) {
                    $rootScope.$broadcast('CATEGORY_DATA_EV', resp.value);

                    angular.forEach(resp.value, function (item) {
                        item.avgPrice = item.sellMoney / item.sellAmount;
                        item.tAvgPrice = item.tSellMoney / item.tSellAmount;
                        item.cAvgPrice = item.cSellMoney / item.cSellAmount;
                    });

                    cb && cb(resp);

                    if (!self.cache) {
                        self.cache = {};
                    }
                    self.cache[catName] = resp;
                }
            });
        },
        getItemCategory: function (catValue, cb) {
            tools.get({
                url: '/marketconditions/category/getItemCategory.htm',
                data: {
                    catValue: catValue
                },
                succ: function (resp) {
                    if (resp.success) {
                        cb && cb(resp);
                    }
                }
            });
        },
        getCategoryByName: function (name, cats) {
            for (var i = 0; i < cats.length; i++) {
                if (cats[i].detailCatName == name) {
                    return cats[i].category;
                }
            }
        },
        dealWord: function (arr) {
            for (var i = 0; i < arr.length; i++) {
                if (arr[i]) {
                    var len = 0;
                    for (var j = 0; j < arr[i].length; j++) {
                        if (arr[i].charCodeAt(j) >= 0 && arr[i].charCodeAt(j) <= 128) {
                            len += 1;
                        } else {
                            len += 2;
                        }

                        if (len >= 8) {

                        }
                    }
                }
            }
        },
        getByteLen: function (str) {
            var len = 0;
            for (var i = 0; i < val.length; i++) {
                var length = val.charCodeAt(i);
                if (length >= 0 && length <= 128) {
                    len += 1;
                } else {
                    len += 2;
                }
            }
            return len; // 24464 36229 32988
        }
    }
}]);